<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="theme-color" content="#0078E7"><meta name="author" content="爱肖彤真是太好了"><meta name="copyright" content="爱肖彤真是太好了"><meta name="generator" content="Hexo 5.1.1"><meta name="theme" content="hexo-theme-yun"><title>魔法方法 | 工藤旧二の博客</title><link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@900&amp;display=swap" media="none" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/star-markdown-css@0.1.19/dist/yun/yun-markdown.min.css"><script src="//at.alicdn.com/t/font_1140697_stqaphw3j4.js" async></script><script src="https://cdn.jsdelivr.net/npm/scrollreveal/dist/scrollreveal.min.js" defer></script><script>document.addEventListener("DOMContentLoaded", () => {
  [".post-card",".post-content img"].forEach((target)=> {
    ScrollReveal().reveal(target);
  })
});
</script><link rel="shortcut icon" type="image/svg+xml" href="/task/yun.ico"><link rel="mask-icon" href="/task/yun.ico" color="#0078E7"><link rel="alternate icon" href="/yun.ico"><link rel="preload" href="/task/css/hexo-theme-yun.css" as="style"><link rel="preload" href="/task/js/utils.js" as="script"><link rel="preload" href="/task/js/hexo-theme-yun.js" as="script"><link rel="prefetch" href="/task/js/sidebar.js" as="script"><link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin><link rel="stylesheet" href="/task/css/hexo-theme-yun.css"><link rel="alternate" href="/task/atom.xml" title="工藤旧二の博客" type="application/atom+xml"><script id="yun-config">
    const Yun = window.Yun || {};
    window.CONFIG = {"root":"/task/","title":"工藤旧二の博客","version":"0.9.7","anonymous_image":"https://cdn.jsdelivr.net/gh/YunYouJun/cdn/img/avatar/none.jpg","say":{"api":"https://v1.hitokoto.cn","hitokoto":true},"local_search":{"path":"/task/search.xml"},"fireworks":{"colors":["102, 167, 221","62, 131, 225","33, 78, 194"]}};
  </script><script>(function(){
  var bp = document.createElement('script');
  var curProtocol = window.location.protocol.split(':')[0];
  if (curProtocol === 'https') {
    bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
  }
  else {
    bp.src = 'http://push.zhanzhang.baidu.com/push.js';
  }
  var s = document.getElementsByTagName("script")[0];
  s.parentNode.insertBefore(bp, s);
})();</script><meta name="description" content="一、__str__改变对象的字符串显示，可以理解为print打印对象的显示 class Student:     def __init__(self, name, age):         self.name &#x3D; name         self.age &#x3D; age      # 定义对象的字符串表示     def __str__(self):         return self.nam">
<meta property="og:type" content="article">
<meta property="og:title" content="魔法方法">
<meta property="og:url" content="http://huang_zhao.gitee.io/task/2020/01/25/python/%E5%AD%A6%E4%B9%A0/python%20%E9%AD%94%E6%B3%95%E6%96%B9%E6%B3%95%E6%80%BB%E7%BB%93/index.html">
<meta property="og:site_name" content="工藤旧二の博客">
<meta property="og:description" content="一、__str__改变对象的字符串显示，可以理解为print打印对象的显示 class Student:     def __init__(self, name, age):         self.name &#x3D; name         self.age &#x3D; age      # 定义对象的字符串表示     def __str__(self):         return self.nam">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-01-25T02:30:17.000Z">
<meta property="article:modified_time" content="2020-08-26T00:59:30.000Z">
<meta property="article:author" content="爱肖彤真是太好了">
<meta property="article:tag" content="python面向对象">
<meta property="article:tag" content="面试">
<meta name="twitter:card" content="summary"><script src="/task/js/ui/mode.js"></script><link rel="stylesheet" href="/task/css/prism.css" type="text/css"></head><body><script defer src="https://cdn.jsdelivr.net/npm/animejs@latest/anime.min.js"></script><script defer src="/task/js/ui/fireworks.js"></script><canvas class="fireworks"></canvas><div class="container"><a class="sidebar-toggle hty-icon-button" id="menu-btn"><div class="hamburger hamburger--spin" type="button"><span class="hamburger-box"><span class="hamburger-inner"></span></span></div></a><div class="sidebar-toggle sidebar-overlay"></div><aside class="sidebar"><script src="/task/js/sidebar.js"></script><ul class="sidebar-nav"><li class="sidebar-nav-item sidebar-nav-toc hty-icon-button sidebar-nav-active" data-target="post-toc-wrap" title="文章目录"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-list-ordered"></use></svg></li><li class="sidebar-nav-item sidebar-nav-overview hty-icon-button" data-target="site-overview-wrap" title="站点概览"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-passport-line"></use></svg></li></ul><div class="sidebar-panel" id="site-overview-wrap"><div class="site-info fix-top"><a class="site-author-avatar" href="/task/about/" title="爱肖彤真是太好了"><img width="96" loading="lazy" src="/task/Yun.png" alt="爱肖彤真是太好了"></a><div class="site-author-name"><a href="/task/about/">爱肖彤真是太好了</a></div><a class="site-name" href="/task/about/site.html">工藤旧二の博客</a><sub class="site-subtitle"></sub><div class="site-desciption"></div></div><nav class="site-state"><a class="site-state-item hty-icon-button icon-home" href="/task/" title="首页"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-home-4-line"></use></svg></span></a><div class="site-state-item"><a href="/task/archives/" title="归档"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-archive-line"></use></svg></span><span class="site-state-item-count">57</span></a></div><div class="site-state-item"><a href="/task/categories/" title="分类"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-folder-2-line"></use></svg></span><span class="site-state-item-count">2</span></a></div><div class="site-state-item"><a href="/task/tags/" title="标签"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-price-tag-3-line"></use></svg></span><span class="site-state-item-count">50</span></a></div><a class="site-state-item hty-icon-button" target="_blank" rel="noopener" href="https://yun.yunyoujun.cn" title="文档"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-settings-line"></use></svg></span></a></nav><hr style="margin-bottom:0.5rem"><div class="links-of-author"><a class="links-of-author-item hty-icon-button" rel="noopener" title="RSS" target="_blank" style="color:orange"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-rss-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" title="QQ" target="_blank" style="color:#12B7F5"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-qq-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" title="GitHub" target="_blank" style="color:#6e5494"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-github-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" title="微博" target="_blank" style="color:#E6162D"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-weibo-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" title="豆瓣" target="_blank" style="color:#007722"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-douban-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" href="https://music.163.com/#/user/home?id=552858287" title="网易云音乐" target="_blank" style="color:#C20C0C"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-netease-cloud-music-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" title="知乎" target="_blank" style="color:#0084FF"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-zhihu-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" href="https://space.bilibili.com/15081363" title="哔哩哔哩" target="_blank" style="color:#FF8EB3"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-bilibili-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" title="Twitter" target="_blank" style="color:#1da1f2"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-twitter-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" title="Telegram Channel" target="_blank" style="color:#0088CC"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-telegram-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" title="E-Mail" target="_blank" style="color:#8E71C1"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-mail-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" title="Travelling" target="_blank" style="color:var(--hty-text-color)"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-send-plane-2-line"></use></svg></a></div><hr style="margin:0.5rem 1rem"><div class="links"><a class="links-item hty-icon-button" href="/task/links/" title="我的小伙伴们" style="color:dodgerblue"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-genderless-line"></use></svg></a></div><br><a class="links-item hty-icon-button" id="toggle-mode-btn" href="javascript:;" title="Mode" style="color: #f1cb64"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-contrast-2-line"></use></svg></a></div><div class="sidebar-panel sidebar-panel-active" id="post-toc-wrap"><div class="post-toc"><div class="post-toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%80%E3%80%81-str"><span class="toc-text">一、__str__</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BA%8C%E3%80%81-repr"><span class="toc-text">二、__repr__</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%89%E3%80%81-format"><span class="toc-text">三、__format__</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9B%9B%E3%80%81-del"><span class="toc-text">四、__del__</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BA%94%E3%80%81-dict-%E5%92%8C-slots"><span class="toc-text">五、__dict__和__slots__</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%85%AD%E3%80%81-item-%E3%80%81-attr-%E7%B3%BB%E5%88%97"><span class="toc-text">六、__item__、__attr__系列</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%83%E3%80%81-init"><span class="toc-text">七、__init__</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%85%AB%E3%80%81-new"><span class="toc-text">八、__new__</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B9%9D%E3%80%81-call"><span class="toc-text">九、__call__</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8D%81%E3%80%81-doc"><span class="toc-text">十、__doc__</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8D%81%E4%B8%80%E3%80%81-iter-%E5%92%8C-next"><span class="toc-text">十一、__iter__和__next__</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8D%81%E4%BA%8C%E3%80%81-enter-%E5%92%8C-exit"><span class="toc-text">十二、__enter__和__exit__</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8D%81%E4%B8%89%E3%80%81-len"><span class="toc-text">十三、__len__</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8D%81%E5%9B%9B%E3%80%81-hash"><span class="toc-text">十四、__hash__</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8D%81%E4%BA%94%E3%80%81-eq"><span class="toc-text">十五、__eq__</span></a></li></ol></div></div></div></aside><main class="sidebar-translate" id="content"><div id="post"><article class="post-block" itemscope itemtype="https://schema.org/Article"><link itemprop="mainEntityOfPage" href="http://huang_zhao.gitee.io/task/task/2020/01/25/python/%E5%AD%A6%E4%B9%A0/python%20%E9%AD%94%E6%B3%95%E6%96%B9%E6%B3%95%E6%80%BB%E7%BB%93/"><span hidden itemprop="author" itemscope itemtype="https://schema.org/Person"><meta itemprop="name" content="爱肖彤真是太好了"><meta itemprop="description"></span><span hidden itemprop="publisher" itemscope itemtype="https://schema.org/Organization"><meta itemprop="name" content="工藤旧二の博客"></span><header class="post-header"><h1 class="post-title" itemprop="name headline">魔法方法</h1><div class="post-meta"><div class="post-time" style="display:block"><span class="post-meta-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-calendar-line"></use></svg></span> <time title="创建时间：2020-01-25 10:30:17" itemprop="dateCreated datePublished" datetime="2020-01-25T10:30:17+08:00">2020-01-25</time><span class="post-meta-divider">-</span><span class="post-meta-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-calendar-2-line"></use></svg></span> <time title="修改时间：2020-08-26 08:59:30" itemprop="dateModified" datetime="2020-08-26T08:59:30+08:00">2020-08-26</time></div><span class="post-count"><span class="post-symbolcount"><span class="post-meta-item-icon" title="本文字数"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-file-word-line"></use></svg></span> <span title="本文字数">2.2k</span><span class="post-meta-divider">-</span><span class="post-meta-item-icon" title="阅读时长"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-timer-line"></use></svg></span> <span title="阅读时长">9m</span></span></span><span class="post-busuanzi"><span class="post-meta-divider">-</span><span class="post-meta-item-icon" title="阅读次数"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-eye-line"></use></svg> <span id="busuanzi_value_page_pv"></span></span></span><div class="post-classify"><span class="post-category"><span class="post-meta-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-folder-line"></use></svg></span> <span itemprop="about" itemscope itemtype="https://schema.org/Thing"><a class="category" href="/task/categories/%E6%8A%80%E6%9C%AF%E5%88%86%E4%BA%AB/" style="--text-color:var(--hty-text-color)" itemprop="url" rel="index"><span itemprop="text">技术分享</span></a></span></span><span class="post-tag"><span class="post-meta-divider">-</span><a class="tag" href="/task/tags/python%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1/" style="--text-color:var(--hty-text-color)"><span class="post-meta-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-price-tag-3-line"></use></svg></span><span class="tag-name">python面向对象</span></a><a class="tag" href="/task/tags/%E9%9D%A2%E8%AF%95/" style="--text-color:var(--hty-text-color)"><span class="post-meta-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-price-tag-3-line"></use></svg></span><span class="tag-name">面试</span></a></span></div></div></header><section class="post-body" itemprop="articleBody"><div class="post-content markdown-body" style="--smc-primary:#0078E7;"><h2 id="一、-str"><a href="#一、-str" class="headerlink" title="一、__str__"></a>一、<code>__str__</code></h2><p>改变对象的字符串显示，可以理解为print打印对象的显示</p>
<pre class=" language-python"><code class="language-python"><span class="token keyword">class</span> <span class="token class-name">Student</span><span class="token punctuation">:</span>
    <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> name<span class="token punctuation">,</span> age<span class="token punctuation">)</span><span class="token punctuation">:</span>
        self<span class="token punctuation">.</span>name <span class="token operator">=</span> name
        self<span class="token punctuation">.</span>age <span class="token operator">=</span> age

    <span class="token comment" spellcheck="true"># 定义对象的字符串表示</span>
    <span class="token keyword">def</span> <span class="token function">__str__</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">return</span> self<span class="token punctuation">.</span>name

s1 <span class="token operator">=</span> Student<span class="token punctuation">(</span><span class="token string">'张三'</span><span class="token punctuation">,</span> <span class="token number">24</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>s1<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 会调用s1的__str__方法</span>
<span class="token operator">>></span><span class="token operator">></span> 张三</code></pre>
<h2 id="二、-repr"><a href="#二、-repr" class="headerlink" title="二、__repr__"></a>二、<code>__repr__</code></h2><p>在python解释器环境下，会默认显示对象的repr表示。</p>
<pre class=" language-python"><code class="language-python"><span class="token operator">>></span><span class="token operator">></span> <span class="token keyword">class</span> <span class="token class-name">Student</span><span class="token punctuation">:</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>     <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> name<span class="token punctuation">,</span> age<span class="token punctuation">)</span><span class="token punctuation">:</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>         self<span class="token punctuation">.</span>name <span class="token operator">=</span> name
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>         self<span class="token punctuation">.</span>age <span class="token operator">=</span> age
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>     <span class="token keyword">def</span> <span class="token function">__repr__</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>         <span class="token keyword">return</span> self<span class="token punctuation">.</span>name
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span> 
<span class="token operator">>></span><span class="token operator">></span> s1 <span class="token operator">=</span> Student<span class="token punctuation">(</span><span class="token string">'张三'</span><span class="token punctuation">,</span> <span class="token number">24</span><span class="token punctuation">)</span>
<span class="token operator">>></span><span class="token operator">></span> s1
张三</code></pre>
<p><strong>总结：</strong></p>
<p>str函数或者print函数调用的是obj.<strong>str</strong>()<br>repr函数或者交互式解释器调用的是obj.<strong>repr</strong>()</p>
<p>注意：<br>如果__str__没有被定义，那么就会使用__repr__来代替输出。<br>__str__和__repr__方法的返回值都必须是字符串。</p>
<h2 id="三、-format"><a href="#三、-format" class="headerlink" title="三、__format__"></a>三、<code>__format__</code></h2><pre class=" language-python"><code class="language-python"><span class="token keyword">class</span> <span class="token class-name">Student</span><span class="token punctuation">:</span>
    <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> name<span class="token punctuation">,</span> age<span class="token punctuation">)</span><span class="token punctuation">:</span>
        self<span class="token punctuation">.</span>name <span class="token operator">=</span> name
        self<span class="token punctuation">.</span>age <span class="token operator">=</span> age

    __format_dict <span class="token operator">=</span> <span class="token punctuation">{</span>
        <span class="token string">'n-a'</span><span class="token punctuation">:</span> <span class="token string">'名字是：{obj.name}-年龄是：{obj.age}'</span><span class="token punctuation">,</span>  <span class="token comment" spellcheck="true"># 名字是：lqz-年龄是：18</span>
        <span class="token string">'n:a'</span><span class="token punctuation">:</span> <span class="token string">'名字是：{obj.name}：年龄是：{obj.age}'</span><span class="token punctuation">,</span>  <span class="token comment" spellcheck="true"># 名字是：lqz：年龄是：18</span>
        <span class="token string">'n/a'</span><span class="token punctuation">:</span> <span class="token string">'名字是：{obj.name}/年龄是：{obj.age}'</span><span class="token punctuation">,</span>  <span class="token comment" spellcheck="true"># 名字是：/年龄是：18</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">def</span> <span class="token function">__format__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> format_spec<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">if</span> <span class="token operator">not</span> format_spec <span class="token operator">or</span> format_spec <span class="token operator">not</span> <span class="token keyword">in</span> self<span class="token punctuation">.</span>__format_dict<span class="token punctuation">:</span>
            format_spec <span class="token operator">=</span> <span class="token string">'n-a'</span>
        fmt <span class="token operator">=</span> self<span class="token punctuation">.</span>__format_dict<span class="token punctuation">[</span>format_spec<span class="token punctuation">]</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span>fmt<span class="token punctuation">)</span> <span class="token comment" spellcheck="true">#{obj.name}:{obj.age}</span>
        <span class="token keyword">return</span> fmt<span class="token punctuation">.</span>format<span class="token punctuation">(</span>obj<span class="token operator">=</span>self<span class="token punctuation">)</span>

s1 <span class="token operator">=</span> Student<span class="token punctuation">(</span><span class="token string">'lqz'</span><span class="token punctuation">,</span> <span class="token number">24</span><span class="token punctuation">)</span>
ret <span class="token operator">=</span> format<span class="token punctuation">(</span>s1<span class="token punctuation">,</span> <span class="token string">'n/a'</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>ret<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># lqz/24</span></code></pre>
<h2 id="四、-del"><a href="#四、-del" class="headerlink" title="四、__del__"></a>四、<code>__del__</code></h2><p>当对象的内存被施放的时候执行</p>
<p>注：此方法一般无须定义，因为Python是一门高级语言，程序员在使用时无需关心内存的分配和释放，因为此工作都是交给Python解释器来执行，所以析构函数的调用是由解释器在进行垃圾回收时自动触发执行的。</p>
<pre class=" language-python"><code class="language-python"><span class="token keyword">class</span> <span class="token class-name">A</span><span class="token punctuation">:</span>
    <span class="token keyword">def</span> <span class="token function">__del__</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'删除了...'</span><span class="token punctuation">)</span>

a <span class="token operator">=</span> A<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>a<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># &lt;__main__.A object at 0x10164fb00></span>
<span class="token keyword">del</span> a  <span class="token comment" spellcheck="true"># 删除了...</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>a<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># NameError: name 'a' is not defined</span></code></pre>
<h2 id="五、-dict-和-slots"><a href="#五、-dict-和-slots" class="headerlink" title="五、__dict__和__slots__"></a>五、<code>__dict__和__slots__</code></h2><p>Python中的类，都会从object里继承一个__dict__属性，这个属性中存放着类的属性和方法对应的键值对。一个类实例化之后，这个类的实例也具有这么一个__dict__属性。但是二者并不相同。</p>
<pre class=" language-python"><code class="language-python"><span class="token keyword">class</span> <span class="token class-name">A</span><span class="token punctuation">:</span>
    some <span class="token operator">=</span> <span class="token number">1</span>

    <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> num<span class="token punctuation">)</span><span class="token punctuation">:</span>
        self<span class="token punctuation">.</span>num <span class="token operator">=</span> num

a <span class="token operator">=</span> A<span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>a<span class="token punctuation">.</span>__dict__<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># {'num': 10}</span>
a<span class="token punctuation">.</span>age <span class="token operator">=</span> <span class="token number">10</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>a<span class="token punctuation">.</span>__dict__<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># {'num': 10, 'age': 10}</span></code></pre>
<p>从上面的例子可以看出来，实例只保存实例的属性和方法，类的属性和方法它是不保存的。正是由于类和实例有__dict__属性，所以类和实例可以在运行过程动态添加属性和方法。</p>
<p>但是由于每实例化一个类都要分配一个__dict__变量，容易浪费内存。因此在Python中有一个内置的__slots__属性。当一个类设置了__slots__属性后，这个类的__dict__属性就不存在了（同理，该类的实例也不存在__dict__属性），如此一来，设置了__slots__属性的类的属性，只能是预先设定好的。</p>
<p>当你定义__slots__后，__slots__就会为实例使用一种更加紧凑的内部表示。实例通过一个很小的固定大小的小型数组来构建的，而不是为每个实例都定义一个__dict__字典，在__slots__中列出的属性名在内部被映射到这个数组的特定索引上。使用__slots__带来的副作用是我们没有办法给实例添加任何新的属性了。</p>
<p>注意：尽管__slots__看起来是个非常有用的特性，但是除非你十分确切的知道要使用它，否则尽量不要使用它。比如定义了__slots__属性的类就不支持多继承。__slots__通常都是作为一种优化工具来使用。–摘自《Python Cookbook》8.4</p>
<p>注意事项：<br>__slots__的很多特性都依赖于普通的基于字典的实现。<br>另外，定义了__slots__后的类不再 支持一些普通类特性了,比如多继承。大多数情况下,你应该只在那些经常被使用到的用作数据结构的类上定义__slots__，比如在程序中需要创建某个类的几百万个实例对象 。<br>关于__slots__的一个常见误区是它可以作为一个封装工具来防止用户给实例增加新的属性。尽管使用__slots__可以达到这样的目的,但是这个并不是它的初衷。它更多的是用来作为一个内存优化工具。</p>
<h2 id="六、-item-、-attr-系列"><a href="#六、-item-、-attr-系列" class="headerlink" title="六、__item__、__attr__系列"></a>六、<code>__item__、__attr__系列</code></h2><pre class=" language-python"><code class="language-python"><span class="token keyword">class</span> <span class="token class-name">Foo</span><span class="token punctuation">:</span>
    <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> name<span class="token punctuation">)</span><span class="token punctuation">:</span>
        self<span class="token punctuation">.</span>name <span class="token operator">=</span> name

    <span class="token keyword">def</span> <span class="token function">__getitem__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> item<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span>self<span class="token punctuation">.</span>__dict__<span class="token punctuation">[</span>item<span class="token punctuation">]</span><span class="token punctuation">)</span>

    <span class="token keyword">def</span> <span class="token function">__setitem__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> key<span class="token punctuation">,</span> value<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'obj[key]=lqz赋值时，执行我'</span><span class="token punctuation">)</span>
        self<span class="token punctuation">.</span>__dict__<span class="token punctuation">[</span>key<span class="token punctuation">]</span> <span class="token operator">=</span> value

    <span class="token keyword">def</span> <span class="token function">__delitem__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> key<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'del obj[key]时，执行我'</span><span class="token punctuation">)</span>
        self<span class="token punctuation">.</span>__dict__<span class="token punctuation">.</span>pop<span class="token punctuation">(</span>key<span class="token punctuation">)</span>

    <span class="token keyword">def</span> <span class="token function">__delattr__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> item<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'del obj.key时，执行我'</span><span class="token punctuation">)</span>
        self<span class="token punctuation">.</span>__dict__<span class="token punctuation">.</span>pop<span class="token punctuation">(</span>item<span class="token punctuation">)</span>

    <span class="token keyword">def</span> <span class="token function">__setattr__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span>key<span class="token punctuation">,</span>value<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'obj.key = value的时候执行我'</span><span class="token punctuation">)</span>
        self<span class="token punctuation">.</span>__dict__<span class="token punctuation">[</span>key<span class="token punctuation">]</span> <span class="token operator">=</span> value

    <span class="token keyword">def</span> <span class="token function">__getattr__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span>item<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'obj.get(key)的时候执行我'</span><span class="token punctuation">)</span>
        <span class="token keyword">return</span> self<span class="token punctuation">[</span>item<span class="token punctuation">]</span>


f1 <span class="token operator">=</span> Foo<span class="token punctuation">(</span><span class="token string">'sb'</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>f1<span class="token punctuation">.</span>__dict__<span class="token punctuation">)</span>
f1<span class="token punctuation">[</span><span class="token string">'age'</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">18</span>
f1<span class="token punctuation">.</span>hobby <span class="token operator">=</span> <span class="token string">'泡妞'</span>
<span class="token keyword">del</span> f1<span class="token punctuation">.</span>hobby
<span class="token keyword">del</span> f1<span class="token punctuation">[</span><span class="token string">'age'</span><span class="token punctuation">]</span>
f1<span class="token punctuation">[</span><span class="token string">'name'</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token string">'lqz'</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>f1<span class="token punctuation">.</span>__dict__<span class="token punctuation">)</span></code></pre>
<h2 id="七、-init"><a href="#七、-init" class="headerlink" title="七、__init__"></a>七、<code>__init__</code></h2><p>使用Python写面向对象的代码的时候我们都会习惯性写一个 <strong>init</strong> 方法，<strong>init</strong> 方法通常用在初始化一个类实例的时候。例如：</p>
<pre class=" language-python"><code class="language-python"><span class="token keyword">class</span> <span class="token class-name">Person</span><span class="token punctuation">:</span>
    <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> name<span class="token punctuation">,</span> age<span class="token punctuation">)</span><span class="token punctuation">:</span>
        self<span class="token punctuation">.</span>name <span class="token operator">=</span> name
        self<span class="token punctuation">.</span>age <span class="token operator">=</span> age

    <span class="token keyword">def</span> <span class="token function">__str__</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">return</span> <span class="token string">'&lt;Person: {}({})>'</span><span class="token punctuation">.</span>format<span class="token punctuation">(</span>self<span class="token punctuation">.</span>name<span class="token punctuation">,</span> self<span class="token punctuation">.</span>age<span class="token punctuation">)</span>

p1 <span class="token operator">=</span> Person<span class="token punctuation">(</span><span class="token string">'张三'</span><span class="token punctuation">,</span> <span class="token number">24</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>p1<span class="token punctuation">)</span></code></pre>
<p>上面是<strong>init__最普通的用法了。但是__init__其实不是实例化一个类的时候第一个被调用的方法。当使用 Persion(name, age) 来实例化一个类时，最先被调用的方法其实是 __new</strong> 方法。</p>
<h2 id="八、-new"><a href="#八、-new" class="headerlink" title="八、__new__"></a>八、<code>__new__</code></h2><p>其实__init__是在类实例被创建之后调用的，它完成的是类实例的初始化操作，而 __new__方法正是创建这个类实例的方法</p>
<pre class=" language-python"><code class="language-python"><span class="token keyword">class</span> <span class="token class-name">Person</span><span class="token punctuation">:</span>

    <span class="token keyword">def</span> <span class="token function">__new__</span><span class="token punctuation">(</span>cls<span class="token punctuation">,</span> <span class="token operator">*</span>args<span class="token punctuation">,</span> <span class="token operator">**</span>kwargs<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'调用__new__，创建类实例'</span><span class="token punctuation">)</span>
        <span class="token keyword">return</span> super<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span>__new__<span class="token punctuation">(</span>Person<span class="token punctuation">)</span>

    <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> name<span class="token punctuation">,</span> age<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'调用__init__，初始化实例'</span><span class="token punctuation">)</span>
        self<span class="token punctuation">.</span>name <span class="token operator">=</span> name
        self<span class="token punctuation">.</span>age <span class="token operator">=</span> age

    <span class="token keyword">def</span> <span class="token function">__str__</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">return</span> <span class="token string">'&lt;Person: {}({})>'</span><span class="token punctuation">.</span>format<span class="token punctuation">(</span>self<span class="token punctuation">.</span>name<span class="token punctuation">,</span> self<span class="token punctuation">.</span>age<span class="token punctuation">)</span>

p1 <span class="token operator">=</span> Person<span class="token punctuation">(</span><span class="token string">'张三'</span><span class="token punctuation">,</span> <span class="token number">24</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>p1<span class="token punctuation">)</span></code></pre>
<p>输出：</p>
<pre class=" language-python"><code class="language-python">调用__new__，创建类实例
调用__init__，初始化实例
<span class="token operator">&lt;</span>Person<span class="token punctuation">:</span> 张三<span class="token punctuation">(</span><span class="token number">24</span><span class="token punctuation">)</span><span class="token operator">></span></code></pre>
<p>__new__方法在类定义中不是必须写的，如果没定义的话默认会调用object.__new__去创建一个对象（因为创建类的时候默认继承的就是object）。</p>
<p>如果我们在类中定义了__new__方法，就是重写了默认的__new__方法，我们可以借此自定义创建对象的行为。</p>
<p>举个例子：</p>
<p>重写类的__new__方法来实现单例模式。</p>
<pre class=" language-python"><code class="language-python"><span class="token keyword">class</span> <span class="token class-name">Singleton</span><span class="token punctuation">:</span>
    <span class="token comment" spellcheck="true"># 重写__new__方法，实现每一次实例化的时候，返回同一个instance对象</span>
    <span class="token keyword">def</span> <span class="token function">__new__</span><span class="token punctuation">(</span>cls<span class="token punctuation">,</span> <span class="token operator">*</span>args<span class="token punctuation">,</span> <span class="token operator">**</span>kw<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">if</span> <span class="token operator">not</span> hasattr<span class="token punctuation">(</span>cls<span class="token punctuation">,</span> <span class="token string">'_instance'</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
            cls<span class="token punctuation">.</span>_instance <span class="token operator">=</span> super<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span>__new__<span class="token punctuation">(</span>Singleton<span class="token punctuation">)</span>
        <span class="token keyword">return</span> cls<span class="token punctuation">.</span>_instance

    <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> name<span class="token punctuation">,</span> age<span class="token punctuation">)</span><span class="token punctuation">:</span>
        self<span class="token punctuation">.</span>name <span class="token operator">=</span> name
        self<span class="token punctuation">.</span>age <span class="token operator">=</span> age


s1 <span class="token operator">=</span> Singleton<span class="token punctuation">(</span><span class="token string">'张三'</span><span class="token punctuation">,</span> <span class="token number">24</span><span class="token punctuation">)</span>
s2 <span class="token operator">=</span> Singleton<span class="token punctuation">(</span><span class="token string">'李四'</span><span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>s1<span class="token punctuation">,</span> s2<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 这两实例都一样</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>s1<span class="token punctuation">.</span>name<span class="token punctuation">,</span> s2<span class="token punctuation">.</span>name<span class="token punctuation">)</span></code></pre>
<h2 id="九、-call"><a href="#九、-call" class="headerlink" title="九、__call__"></a>九、<code>__call__</code></h2><p><strong>call</strong> 方法的执行是由对象后加括号触发的，即：对象()。拥有此方法的对象可以像函数一样被调用。</p>
<pre class=" language-python"><code class="language-python"><span class="token keyword">class</span> <span class="token class-name">Person</span><span class="token punctuation">:</span>
    <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> name<span class="token punctuation">,</span> age<span class="token punctuation">)</span><span class="token punctuation">:</span>
        self<span class="token punctuation">.</span>name <span class="token operator">=</span> name
        self<span class="token punctuation">.</span>age <span class="token operator">=</span> age

    <span class="token keyword">def</span> <span class="token function">__call__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> <span class="token operator">*</span>args<span class="token punctuation">,</span> <span class="token operator">**</span>kwargs<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'调用对象的__call__方法'</span><span class="token punctuation">)</span>

a <span class="token operator">=</span> Person<span class="token punctuation">(</span><span class="token string">'张三'</span><span class="token punctuation">,</span> <span class="token number">24</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 类Person可调用</span>
a<span class="token punctuation">(</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 对象a可以调用</span></code></pre>
<p><strong>注意：</strong> </p>
<p>__new__、__init__、__call__等方法都不是必须写的。</p>
<h2 id="十、-doc"><a href="#十、-doc" class="headerlink" title="十、__doc__"></a>十、<code>__doc__</code></h2><p>定义类的描述信息（注释）</p>
<pre class=" language-python"><code class="language-python"><span class="token keyword">class</span> <span class="token class-name">A</span><span class="token punctuation">:</span>
    <span class="token triple-quoted-string string">"""我是A类的描述信息"""</span>
    <span class="token keyword">pass</span>

<span class="token keyword">print</span><span class="token punctuation">(</span>A<span class="token punctuation">.</span>__doc__<span class="token punctuation">)</span></code></pre>
<h2 id="十一、-iter-和-next"><a href="#十一、-iter-和-next" class="headerlink" title="十一、__iter__和__next__"></a>十一、<code>__iter__和__next__</code></h2><p>如果一个对象拥有了__iter__和__next__方法，那这个对象就是迭代器</p>
<pre class=" language-python"><code class="language-python"><span class="token keyword">class</span> <span class="token class-name">A</span><span class="token punctuation">:</span>
    <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> start<span class="token punctuation">,</span> stop<span class="token operator">=</span>None<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">if</span> <span class="token operator">not</span> stop<span class="token punctuation">:</span>
            start<span class="token punctuation">,</span> stop <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">,</span> start
        self<span class="token punctuation">.</span>start <span class="token operator">=</span> start
        self<span class="token punctuation">.</span>stop <span class="token operator">=</span> stop

    <span class="token keyword">def</span> <span class="token function">__iter__</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">return</span> self

    <span class="token keyword">def</span> <span class="token function">__next__</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">if</span> self<span class="token punctuation">.</span>start <span class="token operator">>=</span> self<span class="token punctuation">.</span>stop<span class="token punctuation">:</span>
            <span class="token keyword">raise</span> StopIteration
        n <span class="token operator">=</span> self<span class="token punctuation">.</span>start
        self<span class="token punctuation">.</span>start <span class="token operator">+=</span> <span class="token number">1</span>
        <span class="token keyword">return</span> n

a <span class="token operator">=</span> A<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">)</span>
<span class="token keyword">from</span> collections <span class="token keyword">import</span> Iterator
<span class="token keyword">print</span><span class="token punctuation">(</span>isinstance<span class="token punctuation">(</span>a<span class="token punctuation">,</span> Iterator<span class="token punctuation">)</span><span class="token punctuation">)</span>

<span class="token keyword">for</span> i <span class="token keyword">in</span> A<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span>

<span class="token keyword">for</span> i <span class="token keyword">in</span> A<span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span>
aaa<span class="token operator">=</span>A<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>next<span class="token punctuation">(</span>aaa<span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>next<span class="token punctuation">(</span>aaa<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true">#抛异常</span></code></pre>
<h2 id="十二、-enter-和-exit"><a href="#十二、-enter-和-exit" class="headerlink" title="十二、__enter__和__exit__"></a>十二、<code>__enter__和__exit__</code></h2><p>一个对象如果实现了__enter__和___exit__方法，那么这个对象就支持上下文管理协议，即with语句</p>
<pre class=" language-python"><code class="language-python"><span class="token keyword">class</span> <span class="token class-name">A</span><span class="token punctuation">:</span>
    <span class="token keyword">def</span> <span class="token function">__enter__</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'进入with语句块时执行此方法，此方法如果有返回值会赋值给as声明的变量'</span><span class="token punctuation">)</span>
        <span class="token keyword">return</span> <span class="token string">'oo'</span>

    <span class="token keyword">def</span> <span class="token function">__exit__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> exc_type<span class="token punctuation">,</span> exc_val<span class="token punctuation">,</span> exc_tb<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'退出with代码块时执行此方法'</span><span class="token punctuation">)</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'1'</span><span class="token punctuation">,</span> exc_type<span class="token punctuation">)</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'2'</span><span class="token punctuation">,</span> exc_val<span class="token punctuation">)</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'3'</span><span class="token punctuation">,</span> exc_tb<span class="token punctuation">)</span>

<span class="token keyword">with</span> A<span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">as</span> f<span class="token punctuation">:</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'进入with语句块'</span><span class="token punctuation">)</span>
    <span class="token comment" spellcheck="true"># with语句中代码块出现异常，则with后的代码都无法执行。</span>
    <span class="token comment" spellcheck="true"># raise AttributeError('sb')</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span>f<span class="token punctuation">)</span> <span class="token comment" spellcheck="true">#f打印出oo</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'嘿嘿嘿'</span><span class="token punctuation">)</span></code></pre>
<h2 id="十三、-len"><a href="#十三、-len" class="headerlink" title="十三、__len__"></a>十三、<code>__len__</code></h2><p>拥有__len__方法的对象支持len(obj)操作。</p>
<pre class=" language-python"><code class="language-python"><span class="token keyword">class</span> <span class="token class-name">A</span><span class="token punctuation">:</span>
    <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
        self<span class="token punctuation">.</span>x <span class="token operator">=</span> <span class="token number">1</span>
        self<span class="token punctuation">.</span>y <span class="token operator">=</span> <span class="token number">2</span>

    <span class="token keyword">def</span> <span class="token function">__len__</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">return</span> len<span class="token punctuation">(</span>self<span class="token punctuation">.</span>__dict__<span class="token punctuation">)</span>

a <span class="token operator">=</span> A<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>len<span class="token punctuation">(</span>a<span class="token punctuation">)</span><span class="token punctuation">)</span></code></pre>
<h2 id="十四、-hash"><a href="#十四、-hash" class="headerlink" title="十四、__hash__"></a>十四、<code>__hash__</code></h2><p>拥有__hash__方法的对象支持hash(obj)操作。</p>
<pre class=" language-python"><code class="language-python"><span class="token keyword">class</span> <span class="token class-name">A</span><span class="token punctuation">:</span>
    <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
        self<span class="token punctuation">.</span>x <span class="token operator">=</span> <span class="token number">1</span>
        self<span class="token punctuation">.</span>x <span class="token operator">=</span> <span class="token number">2</span>

    <span class="token keyword">def</span> <span class="token function">__hash__</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">return</span> hash<span class="token punctuation">(</span>str<span class="token punctuation">(</span>self<span class="token punctuation">.</span>x<span class="token punctuation">)</span> <span class="token operator">+</span> str<span class="token punctuation">(</span>self<span class="token punctuation">.</span>x<span class="token punctuation">)</span><span class="token punctuation">)</span>

a <span class="token operator">=</span> A<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>hash<span class="token punctuation">(</span>a<span class="token punctuation">)</span><span class="token punctuation">)</span></code></pre>
<h2 id="十五、-eq"><a href="#十五、-eq" class="headerlink" title="十五、__eq__"></a>十五、<code>__eq__</code></h2><p>拥有__eq__方法的对象支持相等的比较操作</p>
<pre class=" language-python"><code class="language-python"><span class="token keyword">class</span> <span class="token class-name">A</span><span class="token punctuation">:</span>
    <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span>x<span class="token punctuation">,</span>y<span class="token punctuation">)</span><span class="token punctuation">:</span>
        self<span class="token punctuation">.</span>x <span class="token operator">=</span> x
        self<span class="token punctuation">.</span>y <span class="token operator">=</span> y

    <span class="token keyword">def</span> <span class="token function">__eq__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span>obj<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token comment" spellcheck="true"># 打印出比较的第二个对象的x值</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span>obj<span class="token punctuation">.</span>x<span class="token punctuation">)</span>
        <span class="token keyword">if</span> self<span class="token punctuation">.</span>x <span class="token operator">+</span>self<span class="token punctuation">.</span>y <span class="token operator">==</span> obj<span class="token punctuation">.</span>x<span class="token operator">+</span>obj<span class="token punctuation">.</span>y<span class="token punctuation">:</span>
            <span class="token keyword">return</span> <span class="token boolean">True</span>
        <span class="token keyword">else</span><span class="token punctuation">:</span>
            <span class="token keyword">return</span> <span class="token boolean">False</span>

a <span class="token operator">=</span> A<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">)</span>
b <span class="token operator">=</span> A<span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">1</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>a <span class="token operator">==</span> b<span class="token punctuation">)</span></code></pre>
</div><div id="reward-container"><span class="hty-icon-button button-glow" id="reward-button" title="打赏" onclick="var qr = document.getElementById(&quot;qr&quot;); qr.style.display = (qr.style.display === &quot;none&quot;) ? &quot;block&quot; : &quot;none&quot;;"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-hand-coin-line"></use></svg></span><div id="reward-comment">点我就给你看点有意思的</div><div id="qr" style="display:none;"><div style="display:inline-block"><a target="_blank" rel="noopener" href="https://gitee.com/huang_zhao/hz/raw/master/hz/alipay.png"><img loading="lazy" src="https://gitee.com/huang_zhao/hz/raw/master/hz/alipay.png" alt="支付宝" title="支付宝"></a><div><span style="color:#00A3EE"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-alipay-line"></use></svg></span></div></div><div style="display:inline-block"><a target="_blank" rel="noopener" href="https://gitee.com/huang_zhao/hz/raw/master/hz/qqpay.jpg"><img loading="lazy" src="https://gitee.com/huang_zhao/hz/raw/master/hz/qqpay.jpg" alt="QQ 支付" title="QQ 支付"></a><div><span style="color:#12B7F5"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-qq-line"></use></svg></span></div></div><div style="display:inline-block"><a target="_blank" rel="noopener" href="https://gitee.com/huang_zhao/hz/raw/master/hz/wxpay.jpg"><img loading="lazy" src="https://gitee.com/huang_zhao/hz/raw/master/hz/wxpay.jpg" alt="微信支付" title="微信支付"></a><div><span style="color:#2DC100"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-wechat-pay-line"></use></svg></span></div></div></div></div><ul class="post-copyright"><li class="post-copyright-author"><strong>本文作者：</strong>爱肖彤真是太好了</li><li class="post-copyright-link"><strong>本文链接：</strong><a href="http://huang_zhao.gitee.io/task/2020/01/25/python/%E5%AD%A6%E4%B9%A0/python%20%E9%AD%94%E6%B3%95%E6%96%B9%E6%B3%95%E6%80%BB%E7%BB%93/" title="魔法方法">http://huang_zhao.gitee.io/task/2020/01/25/python/%E5%AD%A6%E4%B9%A0/python%20%E9%AD%94%E6%B3%95%E6%96%B9%E6%B3%95%E6%80%BB%E7%BB%93/</a></li><li class="post-copyright-license"><strong>版权声明：</strong>本博客所有文章除特别声明外，均默认采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" target="_blank" rel="noopener" title="CC BY-NC-SA 4.0 "><svg class="icon"><use xlink:href="#icon-creative-commons-line"></use></svg><svg class="icon"><use xlink:href="#icon-creative-commons-by-line"></use></svg><svg class="icon"><use xlink:href="#icon-creative-commons-nc-line"></use></svg><svg class="icon"><use xlink:href="#icon-creative-commons-sa-line"></use></svg></a> 许可协议。</li></ul></section></article><div class="post-nav"><div class="post-nav-item"><a class="post-nav-prev" href="/task/2020/02/15/python/%E6%A1%86%E6%9E%B6/drf%E2%98%9Ejwt%E8%87%AA%E5%8A%A8%E7%AD%BE%E5%8F%91%E4%B8%8E%E6%89%8B%E5%8A%A8%E7%AD%BE%E5%8F%91/" rel="prev" title="drf☞jwt自动签发与手动签发"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-arrow-left-s-line"></use></svg><span class="post-nav-text">drf☞jwt自动签发与手动签发</span></a></div><div class="post-nav-item"><a class="post-nav-next" href="/task/2020/01/10/go/%E5%9F%BA%E7%A1%80/Go%E5%9F%BA%E7%A1%80%E8%AF%AD%E6%B3%95/" rel="next" title="Go基础语法"><span class="post-nav-text">Go基础语法</span><svg class="icon" aria-hidden="true"><use xlink:href="#icon-arrow-right-s-line"></use></svg></a></div></div></div></main><footer class="sidebar-translate" id="footer"><div class="copyright"><span>&copy; 2019 – 2022 </span><span class="with-love" id="animate"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-cloud-line"></use></svg></span><span class="author"> 爱肖彤真是太好了</span></div><div class="powered"><span>由 <a href="https://hexo.io" target="_blank" rel="noopener">Hexo</a> 驱动 v5.1.1</span><span class="footer-separator">|</span><span>主题 - <a rel="noopener" href="https://github.com/YunYouJun/hexo-theme-yun" target="_blank"><span>Yun</span></a> v0.9.7</span></div><div class="live_time"><span>本博客已萌萌哒地运行</span><span id="display_live_time"></span><span class="moe-text">(●'◡'●)</span><script>function blog_live_time() {
  window.setTimeout(blog_live_time, 1000);
  const start = new Date('2019-04-12T00:00:00');
  const now = new Date();
  const timeDiff = (now.getTime() - start.getTime());
  const msPerMinute = 60 * 1000;
  const msPerHour = 60 * msPerMinute;
  const msPerDay = 24 * msPerHour;
  const passDay = Math.floor(timeDiff / msPerDay);
  const passHour = Math.floor((timeDiff % msPerDay) / 60 / 60 / 1000);
  const passMinute = Math.floor((timeDiff % msPerHour) / 60 / 1000);
  const passSecond = Math.floor((timeDiff % msPerMinute) / 1000);
  display_live_time.innerHTML = " " + passDay + " 天 " + passHour + " 小时 " + passMinute + " 分 " + passSecond + " 秒";
}
blog_live_time();
</script></div><div id="busuanzi"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span id="busuanzi_container_site_uv" title="总访客量"><span><svg class="icon" aria-hidden="true"><use xlink:href="#icon-user-line"></use></svg></span><span id="busuanzi_value_site_uv"></span></span><span class="footer-separator">|</span><span id="busuanzi_container_site_pv" title="总访问量"><span><svg class="icon" aria-hidden="true"><use xlink:href="#icon-eye-line"></use></svg></span><span id="busuanzi_value_site_pv"></span></span></div></footer><a class="hty-icon-button" id="goUp" aria-label="back-to-top" href="#"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-arrow-up-s-line"></use></svg><svg class="progress-circle-container" viewBox="0 0 100 100"><circle class="progress-circle" id="progressCircle" cx="50" cy="50" r="48" fill="none" stroke="#0078E7" stroke-width="2" stroke-linecap="round"></circle></svg></a><a class="popup-trigger hty-icon-button icon-search" id="search" href="javascript:;" title="搜索"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-search-line"></use></svg></span></a><script>window.addEventListener("DOMContentLoaded", () => {
  // Handle and trigger popup window
  document.querySelector(".popup-trigger").addEventListener("click", () => {
    document.querySelector(".popup").classList.add("show");
    setTimeout(() => {
      document.querySelector(".search-input").focus();
    }, 100);
  });

  // Monitor main search box
  const onPopupClose = () => {
    document.querySelector(".popup").classList.remove("show");
  };

  document.querySelector(".popup-btn-close").addEventListener("click", () => {
    onPopupClose();
  });

  window.addEventListener("keyup", event => {
    if (event.key === "Escape") {
      onPopupClose();
    }
  });
});
</script><script src="/task/js/search/local-search.js" defer></script><div class="popup search-popup"><div class="search-header"><span class="popup-btn-close close-icon hty-icon-button"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-close-line"></use></svg></span></div><div class="search-input-container"><input class="search-input" id="local-search-input" type="text" placeholder="搜索..." value=""></div><div id="local-search-result"></div></div></div><script defer src="/task/js/utils.js"></script><script defer src="/task/js/hexo-theme-yun.js"></script></body></html>